using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Reflection;
using System.Web.Mvc;
using System.Web.Routing;
using Isis.Controllers;
using Isis.Interfaces;
using ControllerBase = Isis.Controllers.ControllerBase;

namespace Isis
{
    public class IsisControllerFactory : IControllerFactory
    {
        private const string BASE_ISIS_CONTROLPANEL_URL = "/isis";

        public IController CreateController(RequestContext requestContext, string controllerName)
        {
            IEnumerable<ControllerBase> allControllers = from t in Assembly.GetExecutingAssembly().GetTypes()
                            where t.BaseType == typeof(ControllerBase)
                                     && t.GetConstructor(Type.EmptyTypes) != null
                                                         select Activator.CreateInstance(t) as ControllerBase;

            ControllerBase controller = allControllers.SingleOrDefault(c => c.GetType().Name.Contains(controllerName));

            return controller;
        }

        public void ReleaseController(IController controller)
        {
            if (controller is IDisposable)
                (controller as IDisposable).Dispose();
            else
                controller = null;
        }
    }
}